package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.shiro
 * @Description:
 * @Date 2022/10/12 20:18l.
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    DtsAdminService adminService;

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;

//    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        DtsAdmin admin = (DtsAdmin) principals.getPrimaryPrincipal();
        Integer[] ids = admin.getRoleIds();
        //角色  的set集合
        Set<String> roles = roleService.findRoleById(ids);
        authorizationInfo.setRoles(roles);

        //权限的set集合
        Set<String> perms = permissionService.findById(ids);
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }

//    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        // 根据用户名 查询用户信息
        DtsAdmin admin = adminService.findByUsername(username);

        if (admin==null){
            throw new UnknownAccountException("未知的账户");
        }
        //密文跟原文校验
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(password,admin.getPassword())){
            throw new CredentialsException("密码错误");
        }
        //判断账户 是否被锁定
        if (admin.getDeleted()){
            throw new LockedAccountException("账户被锁定");
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin,password,admin.getUsername());

        return authenticationInfo;
    }
}
